package com.xiaoq.distribution.endpoint;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.dubbo.config.annotation.Reference;
import com.xiaoq.RedisTemplate4JedisCluster;
import com.xiaoq.apis.sites.ISitesApi;
import com.xiaoq.apis.sites.SitesInfo4SocialVo;
import com.xiaoq.coms.GenericDataResponse;
import com.xiaoq.coms.GenericListResponse;
import com.xiaoq.coms.GenericResponse;
import com.xiaoq.coms.util.ConstantUtil;
import com.xiaoq.coms.util.IdGenerator;
import com.xiaoq.distribution.entity.DistributorEntity;
import com.xiaoq.distribution.service.IDistributorService;
import com.xiaoq.distribution.vo.DistributorVo;
import com.xiaoq.vo.PagingVo;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;

@RestController
@RequestMapping(value = "/api/v1/distributor")
@Api(tags={"分销商相关Api"})
public class DistributorEndpoint {
	
	private static final Logger LOG = LoggerFactory.getLogger(DistributorEndpoint.class);
	
	@Reference(interfaceClass=ISitesApi.class,check=false,version="1.0.0")
	private ISitesApi sitesApi;
	
	@Autowired
	private IdGenerator idGenerator;
	
	@Autowired
	private IDistributorService distributorSer;
	
	@Autowired
	private RedisTemplate4JedisCluster redisTemplate;
	
	private class SecretKeyDataResponse extends GenericDataResponse<String> {}
	private class DistributorListGenericResponse extends GenericListResponse<DistributorVo> {}
	private class DistributorDataGenericResponse extends GenericDataResponse<DistributorVo> {}
	
	@ApiOperation(value = "新增分销商", notes = "新增分销商")
	@ApiResponses({ @ApiResponse(code = 200, response = GenericResponse.class, message = "新增分销商") })
	@PostMapping(value = "", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
	public ResponseEntity<?> addDistributor(@RequestBody DistributorVo distributorVo,HttpServletRequest request) {
		String userId = (String) request.getAttribute("userId");
		String shopId = redisTemplate.get(ConstantUtil.REDIS_PREFIX_MANAGER_SHOP_RELATION, userId);
		SitesInfo4SocialVo sitesInfo = sitesApi.getSiteInfo4Social(shopId);
		DistributorEntity distributor = new DistributorEntity();
		String name = distributorVo.getName();
		DistributorEntity distributorInDB = distributorSer.findByname(name);
		if(distributorInDB!=null){
			return GenericResponse.ng("分销商名字重复！");
		}
		BeanUtils.copyProperties(distributorVo, distributor);
		String clientId = idGenerator.nextId();
		String id = idGenerator.nextId();
		String secretKey = UUID.randomUUID().toString();
		distributor.setClientId(clientId);
		distributor.setId(id);
		distributor.setSecretKey(secretKey);
		distributor.setShopId(shopId);
		distributor.setMerchantId(sitesInfo.getMerchantId());
		distributor.setIsAgree(ConstantUtil.DISTRIBUTION_NOT_AGREEMENT);
		distributorSer.addDistributor(distributor);
		return GenericResponse.ok();
		
	}
	
	@ApiOperation(value = "编辑分销商", notes = "编辑分销商")
	@ApiResponses({ @ApiResponse(code = 200, response = GenericResponse.class, message = "编辑分销商") })
	@PutMapping(value = "", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
	public ResponseEntity<?> editDistributor(@RequestBody DistributorVo distributorVo,HttpServletRequest request) {
		String id = distributorVo.getId();
		DistributorEntity distributor = distributorSer.findById(id);
		if(distributor==null){
			return GenericResponse.ng("编辑的分销商不存在！");
		}
		String name = distributorVo.getName();
		String name2 = distributor.getName();
		if(name.equals(name2)){
			return GenericResponse.ng("分销商名字重复！");
		}
		if(StringUtils.isNotBlank(name)){
			distributor.setName(name);
		}
		String creditImg = distributorVo.getCreditImg();
		if(StringUtils.isNotBlank(creditImg)){
			distributor.setCreditImg(creditImg);
		}
		String balanceMobile = distributorVo.getBalanceMobile();
		if(StringUtils.isBlank(balanceMobile)){
			distributor.setBalanceMobile(balanceMobile);
		}
		
		String operationMobile = distributor.getOperationMobile();
		if(StringUtils.isBlank(operationMobile)){
			distributor.setOperationMobile(operationMobile);
		}
		String settleCycle = distributor.getSettleCycle();
		if(StringUtils.isBlank(settleCycle)){
			distributor.setSettleCycle(settleCycle);
		}
		Integer settleTime = distributor.getSettleTime();
		if(settleTime!=null){
			distributor.setSettleTime(settleTime);
			
		}
		distributorSer.addDistributor(distributor);
		return GenericResponse.ok();
		
	}
	
	@ApiOperation(value = "查找SecretKey", notes = "查找SecretKey")
	@ApiResponses({ @ApiResponse(code = 200, response = SecretKeyDataResponse.class, message = "查找SecretKey") })
	@GetMapping(value = "/secretKey", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
	public ResponseEntity<?> findSecretKey(@RequestParam(value="id")@ApiParam(value="分销商Id")String id) {
		DistributorEntity distributor = distributorSer.findById(id);
		if(distributor==null){
			return GenericResponse.ng("编辑的分销商不存在！");
		}
		String secretKey = UUID.randomUUID().toString();
		distributor.setSecretKey(secretKey);
		distributorSer.addDistributor(distributor);
		return GenericDataResponse.okWithData(secretKey);
		
	}
	
	@ApiOperation(value = "分销商列表", notes = "分销商列表")
	@ApiResponses({ @ApiResponse(code = 200, response = DistributorListGenericResponse.class, message = "分销商列表") })
	@GetMapping(value = "", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
	public ResponseEntity<?> findDistributors(@ModelAttribute(value = "pvo") PagingVo pvo, HttpServletRequest request) {
		String userId = (String) request.getAttribute("userId");
		String shopId = redisTemplate.get(ConstantUtil.REDIS_PREFIX_MANAGER_SHOP_RELATION, userId);
		List<DistributorEntity> distributors = distributorSer.findByShopId(shopId,pvo);
		List<DistributorVo> distributorList = new ArrayList<>();
		DistributorVo distributorVo = null;
		for(DistributorEntity distributor:distributors){
			distributorVo = new DistributorVo();
			BeanUtils.copyProperties(distributor, distributorVo);
			distributorList.add(distributorVo);
		}
		return DistributorListGenericResponse.listAndCount(distributorList, (Long)pvo.getTc());
		
	}
	
	@ApiOperation(value = "编辑回显", notes = "编辑回显")
	@ApiResponses({ @ApiResponse(code = 200, response = DistributorDataGenericResponse.class, message = "编辑回显") })
	@GetMapping(value = "/detail", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
	public ResponseEntity<?> findDistributor(@RequestParam(value="id")@ApiParam(value="分销商Id")String id) {
		DistributorEntity distributor = distributorSer.findById(id);
		if(distributor==null){
			return GenericResponse.ng("编辑的分销商不存在！");
		}
		DistributorVo distributorVo = new DistributorVo();
		BeanUtils.copyProperties(distributor, distributorVo);
		return GenericDataResponse.okWithData(distributorVo);
		
	}
	
	@ApiOperation(value = "合同添加的时候的分销商列表", notes = "合同添加的时候的分销商列表")
	@ApiResponses({ @ApiResponse(code = 200, response = DistributorListGenericResponse.class, message = "合同添加的时候的分销商列表") })
	@GetMapping(value = "/list4agreement", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
	public ResponseEntity<?> findDistributors4Agreement(HttpServletRequest request) {
		String userId = (String) request.getAttribute("userId");
		String shopId = redisTemplate.get(ConstantUtil.REDIS_PREFIX_MANAGER_SHOP_RELATION, userId);
		List<DistributorEntity> distributors = distributorSer.findByShopId4Agreement(shopId);
		List<DistributorVo> distributorList = new ArrayList<>();
		DistributorVo distributorVo = null;
		for(DistributorEntity distributor:distributors){
			distributorVo = new DistributorVo();
			BeanUtils.copyProperties(distributor, distributorVo);
			distributorList.add(distributorVo);
		}
		return DistributorListGenericResponse.listNoCount(distributorList);
		
	}

}
